<?php
	include_once("../../MasterPages/headerPHPScript.php");
	$CourseDocumentService = new CourseDocumentService();
	$CourseID = $_GET["CourseID"];
	$CourseDocumentID = ISSET($_GET["CourseDocumentID"]) ? $_GET["CourseDocumentID"] : "";
	
	$CourseDocumentEntity = new CourseDocumentEntity();
	$CourseDocumentEntity->CourseID = $CourseID;
	$CourseDocumentEntity->Description = $_POST["txtDescription"];

	if(ISSET($_FILES["fileUpload"]['name']) && $_FILES["fileUpload"]['name']!=""){
		$FilePath = "/Resources/Files/CourseDocuments/$CourseID/";
		$upload_path = dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME']))) . $FilePath;
		
		if (!file_exists($upload_path)) {
			mkdir($upload_path, 0777, true);
		}	
	
		$filename = $_FILES['fileUpload']['name'];
		$CourseDocumentEntity->FileName = $filename;
		$CourseDocumentEntity->FilePath = ".." . $FilePath;
		move_uploaded_file($_FILES['fileUpload']['tmp_name'],$upload_path . $filename);
	}

	if($CourseDocumentID!=""){
		$CourseDocumentEntity = $CourseDocumentService->TeacherGetCourseDocumentByCourseDocumentID($CourseDocumentID);
		$FilePath = $CourseDocumentEntity->FilePath;
		if($FilePath!=""){
			$upload_path = dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME']))) . str_replace("../","/",$FilePath);
			DeleteFile($upload_path);
			$directory = str_replace($FileName,"",$upload_path);			
			DeleteEmptyFolder($directory);
		}

		$CourseDocumentService->DeleteCourseDocument($CourseDocumentID);
	}else{
		$CourseDocumentService->InsertCourseDocument($CourseDocumentEntity);
	}
	header("location:../index.php?page=teacher-course-document.php&CourseID=$CourseID");
?>